package com.wenzhoujie;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;

import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDResourcesUtil;
import com.wenzhoujie.library.utils.SDToast;
import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.event.EventTagJpush;
import com.wenzhoujie.fragment.TuanDetailAttrsFragment;
import com.wenzhoujie.fragment.TuanDetailCommentFragment;
import com.wenzhoujie.fragment.TuanDetailFirstFragment;
import com.wenzhoujie.fragment.TuanDetailOtherMerchantFragment;
import com.wenzhoujie.fragment.TuanDetailSecondFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.SearchConditionModel;
import com.wenzhoujie.model.act.Collect_dealActModel;
import com.wenzhoujie.model.act.GoodsdescActModel;
import com.wenzhoujie.umeng.UmengSocialManager;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.ViewInject;

public class TuanDetailActivity extends BaseActivity implements OnClickListener
{

	/** 商品id */
	public static final String EXTRA_GOODS_ID = "extra_goods_id";

	/** 是否是团购商品的详情 1:是团购商品, 0:普通商品 */
	public static final String EXTRA_GOODS_TYPE = "extra_goods_type";

	@ViewInject(id = R.id.act_tuan_detail_fl_container_first)
	private FrameLayout mFlContainerFirst = null;

	@ViewInject(id = R.id.act_tuan_detail_fl_container_second)
	private FrameLayout mFlContainerSecond = null;

	@ViewInject(id = R.id.act_tuan_detail_fl_container_third)
	private FrameLayout mFlContainerThird = null;

	@ViewInject(id = R.id.act_tuan_detail_fl_container_four)
	private FrameLayout mFlContainerFour = null;

	@ViewInject(id = R.id.act_tuan_detail_fl_container_five)
	private FrameLayout mFlContainerFive = null;

	private SearchConditionModel mSearcher = new SearchConditionModel();

	private String mStrGoodsId = null;

	private GoodsdescActModel mGoodsModel = null;

	private TuanDetailFirstFragment mFragFirst = null;
	private TuanDetailSecondFragment mFragSecond = null;
	private TuanDetailOtherMerchantFragment mFragOtherMerchant = null;
	private TuanDetailAttrsFragment mFragFour = null;
	private TuanDetailCommentFragment mFragFive = null;

	private int mCollectStatus = 2; // 传给web端的参数 2:加载,1:增加收藏,0取消收藏;

	private boolean isCollected = false;

	private int mGoodsType;

	public TuanDetailSecondFragment getmFragSecond()
	{
		return mFragSecond;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_TWO_RIGHT_BUTTON);
		setContentView(R.layout.act_tuan_detail);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		getIntentData();
		initTitle();
		initCollectBtn();
		requestIsCollect();
		requestGoodsDetail();
	}

	@Override
	protected void onNewIntent(Intent intent)
	{
		setIntent(intent);
		mCollectStatus = 2;
		init();
		super.onNewIntent(intent);
	}

	private void initTitle()
	{
		mTitleTwoRightBtns.setmListener(new SDTitleTwoRightButtonListener()
		{

			@Override
			public void onRightButton2CLick_SDTitleTwoRightButton(View v)
			{
				clickCollect();
			}

			@Override
			public void onRightButton1CLick_SDTitleTwoRightButton(View v)
			{
				clickShare();
			}

			@Override
			public void onLeftButtonCLick_SDTitleTwoRightButton(View v)
			{
				finish();
			}
		});

		mTitleTwoRightBtns.setTitleTop(SDResourcesUtil.getString(R.string.detail));
		if (mGoodsType == 0)
		{
			mTitleTwoRightBtns.setTitleTop(SDResourcesUtil.getString(R.string.goods_detail));
		} else if (mGoodsType == 1)
		{
			mTitleTwoRightBtns.setTitleTop(SDResourcesUtil.getString(R.string.tuan_gou_detail));
		}

//		mTitleTwoRightBtns.setRightImage1(R.drawable.ic_tuan_detail_share);
		mTitleTwoRightBtns.setRightImage2(R.drawable.ic_tuan_detail_collection);
	}

	private void initCollectBtn()
	{
		if (isCollected)
		{
			mTitleTwoRightBtns.setRightImage2(R.drawable.ic_tuan_detail_collection);
		} else
		{
			mTitleTwoRightBtns.setRightImage2(R.drawable.ic_tuan_detail_un_collection);
		}

	}

	/**
	 * 请求是否收藏接口
	 */
	private void requestIsCollect()
	{
		if (mStrGoodsId != null)
		{
			if (App.getApplication().getmLocalUser() == null)
			{
				// TODO跳到登录界面

			} else
			{
				RequestModel model = new RequestModel();
				model.put("act", "collect_deal");
				model.put("deal_id", mStrGoodsId);
				model.put("email", mSearcher.getEmail());
				model.put("pwd", mSearcher.getPwd());
				model.put("collect_status", mCollectStatus); // 传给web端的参数
																// 2:加载,1:增加收藏,0取消收藏;
				RequestCallBack<String> handler = new RequestCallBack<String>()
				{

					@Override
					public void onStart()
					{
						AppHelper.showLoadingDialog("请稍候...");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo)
					{
						Collect_dealActModel actModel = JsonUtil.json2Object(responseInfo.result, Collect_dealActModel.class);
						if (!SDInterfaceUtil.isActModelNull(actModel))
						{
							if (actModel.getResponse_code() == 1)
							{
								if (actModel.getIs_collect() == 0)
								{
									isCollected = false;
									mCollectStatus = 1; // 未收藏，则点击后应该传入1，表示要收藏
								} else
								{
									isCollected = true;
									mCollectStatus = 0;// 已收藏，则点击后应该传入0，表示要取消收藏
								}
							} else
							{
								SDToast.showToast("请求失败");
								mCollectStatus = 2;
							}
							initCollectBtn();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg)
					{
						mCollectStatus = 2;
						SDToast.showToast("请求失败");
					}

					@Override
					public void onFinish()
					{
						AppHelper.hideLoadingDialog();
					}
				};
				InterfaceServer.getInstance().requestInterface(model, handler);
			}
		}

	}

	/**
	 * 请求商品详情接口
	 */
	private void requestGoodsDetail()
	{
		if (mStrGoodsId != null)
		{
			RequestModel model = new RequestModel();
			model.put("act", "goodsdesc");
			model.put("id", mStrGoodsId);
			model.put("email", mSearcher.getEmail());
			model.put("pwd", mSearcher.getPwd());
			model.put("m_latitude", mSearcher.getM_latitude());
			model.put("m_longitude", mSearcher.getM_longitude());
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					GoodsdescActModel actModel = new Gson().fromJson(responseInfo.result, GoodsdescActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						mGoodsModel = actModel;
						addFragments(actModel);
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					AppHelper.hideLoadingDialog();
				}
			};
			InterfaceServer.getInstance().requestInterface(model, handler);
		}
	}

	private void getIntentData()
	{
		Intent intent = getIntent();
		mStrGoodsId = intent.getStringExtra(EXTRA_GOODS_ID);
		mGoodsType = intent.getIntExtra(EXTRA_GOODS_TYPE, -1);
	}

	/**
	 * 添加fragment
	 */
	private void addFragments(GoodsdescActModel goodsModel)
	{
		if (goodsModel == null)
		{
			return;
		}

		mFragFirst = new TuanDetailFirstFragment();
		mFragFirst.setmGoodsModel(goodsModel);
		addFragment(mFragFirst, R.id.act_tuan_detail_fl_container_first);

		mFragSecond = new TuanDetailSecondFragment();
		mFragSecond.setmGoodsModel(goodsModel);
		addFragment(mFragSecond, R.id.act_tuan_detail_fl_container_second);

		// ---------------商品属性----------------
		mFragFour = new TuanDetailAttrsFragment();
		mFragFour.setmGoodsModel(goodsModel);
		addFragment(mFragFour, R.id.act_tuan_detail_fl_container_third);
		
		// ---------------其他门店----------------
		mFragOtherMerchant = new TuanDetailOtherMerchantFragment();
		mFragOtherMerchant.setmGoodsModel(goodsModel);
		addFragment(mFragOtherMerchant, R.id.act_tuan_detail_fl_container_four);

		// ---------------评论----------------
		mFragFive = new TuanDetailCommentFragment();
		mFragFive.setmGoodsModel(goodsModel);
		addFragment(mFragFive, R.id.act_tuan_detail_fl_container_five);

	}

	@Override
	public void onClick(View v)
	{
	}

	/**
	 * 分享
	 */
	private void clickShare()
	{
		if (mGoodsModel != null)
		{
			String content = mGoodsModel.getShare_content();
			String imageUrl = mGoodsModel.getImage();
			String clickUrl = null;

			if (!TextUtils.isEmpty(content))
			{
				if (content.contains("http://"))
				{
					clickUrl = content.substring(content.indexOf("http://"));
				} else
				{
					clickUrl = ApkConstant.SERVER_API_URL_PRE + ApkConstant.SERVER_API_URL_MID;
				}
			}
			UmengSocialManager.openShare("分享", content, imageUrl, clickUrl, this, new SnsPostListener()
			{

				@Override
				public void onStart()
				{

				}

				@Override
				public void onComplete(SHARE_MEDIA arg0, int arg1, SocializeEntity arg2)
				{

				}
			});
		}
	}

	/**
	 * 收藏
	 */
	private void clickCollect()
	{
		if (App.getApplication().getmLocalUser() == null)
		{
			SDToast.showToast("登陆后才可以收藏");
			startActivity(new Intent(getApplicationContext(), LoginNewActivity.class));
		} else
		{
			requestIsCollect();
		}

	}

	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		if (EventTagJpush.EVENT_TUANDETAIL_ID.equals(event.getEventTagString()))
		{
			finish();
		}
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		if (App.getApplication().mRuntimeConfig.isNeedRefreshTuanDetail())
		{
			mCollectStatus = 2;
			init();
			App.getApplication().mRuntimeConfig.setNeedRefreshTuanDetail(false);
		}
	}

}